<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>审核详情 - 沥青运输管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background-color: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .image-gallery {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .image-gallery img {
            max-width: 200px;
            max-height: 200px;
            border: 1px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
        }
        .modal-img {
            max-width: 100%;
            max-height: 80vh;
        }
        .disabled-link {
            cursor: not-allowed;
            opacity: 0.6;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <span data-feather="home"></span>
                                仪表板
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/review/">
                                <span data-feather="check-circle"></span>
                                审核管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="users"></span>
                                用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="truck"></span>
                                车辆管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="package"></span>
                                订单管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/profile/">
                                <span data-feather="user"></span>
                                个人中心
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">审核详情</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="/review/list/" class="btn btn-sm btn-outline-secondary">
                                返回列表
                            </a>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0" id="reviewTitle">加载中...</h5>
                            </div>
                            <div class="card-body">
                                <div id="reviewDetail">
                                    <div class="text-center py-5">
                                        <div class="spinner-border" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 状态统计卡片 -->
                <div class="row mt-4">
                    <div class="col-md-4 mb-4">
                        <div class="card text-white bg-warning" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=pending'">
                            <div class="card-body">
                                <h5 class="card-title">待审核</h5>
                                <h2 id="pendingCount">-</h2>
                                <p class="card-text">需要尽快处理的申请</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card text-white bg-success" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=approved'">
                            <div class="card-body">
                                <h5 class="card-title">已通过</h5>
                                <h2 id="approvedCount">-</h2>
                                <p class="card-text">已审核通过的申请</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card text-white bg-danger" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=rejected'">
                            <div class="card-body">
                                <h5 class="card-title">已拒绝</h5>
                                <h2 id="rejectedCount">-</h2>
                                <p class="card-text">不符合要求的申请</p>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 审核操作模态框 -->
    <div class="modal fade" id="approveModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">审核操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="approveForm">
                        <input type="hidden" id="reviewId" name="reviewId">
                        <div class="mb-3">
                            <label class="form-label">审核结果</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="approved">通过</option>
                                <option value="rejected">拒绝</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="reason" class="form-label">审核说明</label>
                            <textarea class="form-control" id="reason" name="reason" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitApprove">提交</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片放大模态框 -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-body text-center">
                    <img id="enlargedImage" class="modal-img" src="" alt="">
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 获取URL中的审核ID
        const urlParams = new URLSearchParams(window.location.search);
        const reviewId = urlParams.get('id') || window.location.pathname.split('/')[3];
        
        // 页面加载完成后获取审核详情
        document.addEventListener('DOMContentLoaded', function() {
            if (reviewId) {
                fetchReviewDetail(reviewId);
            }
            
            // 绑定提交事件
            document.getElementById('submitApprove').onclick = function() {
                submitApprove(reviewId);
            };
            
            // 获取统计信息
            fetchStats();
        });
        
        // 获取统计信息
        function fetchStats() {
            // 获取待审核数量
            fetch('/api/admin/review/pending/')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('pendingCount').textContent = data.count || 0;
                })
                .catch(error => {
                    console.error('获取待审核数量失败:', error);
                    document.getElementById('pendingCount').textContent = '错误';
                });
            
            // 获取总的统计信息
            fetch('/api/admin/review/history/')
                .then(response => response.json())
                .then(data => {
                    const stats = {
                        approved: 0,
                        rejected: 0
                    };
                    
                    if (data.results) {
                        data.results.forEach(review => {
                            if (review.status === 'approved') stats.approved++;
                            else if (review.status === 'rejected') stats.rejected++;
                        });
                        
                        document.getElementById('approvedCount').textContent = stats.approved;
                        document.getElementById('rejectedCount').textContent = stats.rejected;
                    }
                })
                .catch(error => {
                    console.error('获取统计信息失败:', error);
                });
        }
        
        // 获取审核详情
        function fetchReviewDetail(id) {
            fetch(`/api/admin/review/${id}/`)
                .then(response => response.json())
                .then(review => {
                    renderReviewDetail(review);
                })
                .catch(error => {
                    console.error('获取审核详情失败:', error);
                    document.getElementById('reviewDetail').innerHTML = `
                        <div class="alert alert-danger" role="alert">
                            加载审核详情失败，请稍后重试。
                        </div>
                    `;
                });
        }
        
        // 渲染审核详情
        function renderReviewDetail(review) {
            document.getElementById('reviewTitle').textContent = `${getReviewTypeDisplay(review.type)} #${review.id}`;
            
            let html = `
                <div class="row">
                    <div class="col-md-6">
                        <h6>基本信息</h6>
                        <table class="table table-borderless">
                            <tr>
                                <td><strong>审核类型:</strong></td>
                                <td>${getReviewTypeDisplay(review.type)}</td>
                            </tr>
                            <tr>
                                <td><strong>状态:</strong></td>
                                <td>
                                    <span class="badge ${getStatusClass(review.status)}">
                                        ${getStatusDisplay(review.status)}
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td><strong>提交时间:</strong></td>
                                <td>${formatDate(review.submitted_at)}</td>
                            </tr>
                            ${review.reviewed_at ? `
                            <tr>
                                <td><strong>审核时间:</strong></td>
                                <td>${formatDate(review.reviewed_at)}</td>
                            </tr>
                            ` : ''}
                            ${review.reviewer ? `
                            <tr>
                                <td><strong>审核员:</strong></td>
                                <td>${review.reviewer}</td>
                            </tr>
                            ` : ''}
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6>关联信息</h6>
                        ${review.type === 'user' && review.user ? `
                        <table class="table table-borderless">
                            <tr>
                                <td><strong>用户:</strong></td>
                                <td>${review.user.phone}</td>
                            </tr>
                            <tr>
                                <td><strong>公司:</strong></td>
                                <td>${review.user.company || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>信用评分:</strong></td>
                                <td>${review.user.credit_score}</td>
                            </tr>
                        </table>
                        ` : ''}
                        ${review.type === 'vehicle' && review.vehicle ? `
                        <table class="table table-borderless">
                            <tr>
                                <td><strong>车牌号:</strong></td>
                                <td>${review.vehicle.license_plate}</td>
                            </tr>
                            <tr>
                                <td><strong>车辆类型:</strong></td>
                                <td>${review.vehicle.vehicle_type_display || review.vehicle.vehicle_type}</td>
                            </tr>
                            <tr>
                                <td><strong>载重:</strong></td>
                                <td>${review.vehicle.capacity} 吨</td>
                            </tr>
                            <tr>
                                <td><strong>车主:</strong></td>
                                <td>${review.vehicle.user.phone}</td>
                            </tr>
                        </table>
                        ` : ''}
                    </div>
                    ${review.type === 'user' && review.user_profile ? `
                    <div class="col-12">
                        <h6>用户资质信息</h6>
                        <table class="table table-borderless">
                            <tr>
                                <td><strong>真实姓名:</strong></td>
                                <td>${review.user_profile.real_name || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>身份证号:</strong></td>
                                <td>${review.user_profile.id_card || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>地址:</strong></td>
                                <td>${review.user_profile.address || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>公司名称:</strong></td>
                                <td>${review.user.company || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>营业执照号:</strong></td>
                                <td>${review.user_profile.business_license || '无'}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-12">
                        <h6>相关证件图片</h6>
                        <div class="image-gallery">
                            ${review.user_profile.id_card_front_image ? `
                            <div>
                                <p>身份证正面</p>
                                <img src="${review.user_profile.id_card_front_image}" alt="身份证正面" class="img-thumbnail" onclick="enlargeImage('${review.user_profile.id_card_front_image}')">
                            </div>
                            ` : ''}
                            ${review.user_profile.driver_license_image ? `
                            <div>
                                <p>驾驶证</p>
                                <img src="${review.user_profile.driver_license_image}" alt="驾驶证" class="img-thumbnail" onclick="enlargeImage('${review.user_profile.driver_license_image}')">
                            </div>
                            ` : ''}
                            ${review.user_profile.business_license_image ? `
                            <div>
                                <p>营业执照</p>
                                <img src="${review.user_profile.business_license_image}" alt="营业执照" class="img-thumbnail" onclick="enlargeImage('${review.user_profile.business_license_image}')">
                            </div>
                            ` : ''}
                        </div>
                    </div>
                    ` : ''}
                    ${review.type === 'vehicle' && review.vehicle ? `
                    <div class="col-12">
                        <h6>车辆信息</h6>
                        <table class="table table-borderless">
                            <tr>
                                <td><strong>车牌号:</strong></td>
                                <td>${review.vehicle.license_plate}</td>
                            </tr>
                            <tr>
                                <td><strong>车辆类型:</strong></td>
                                <td>${review.vehicle.vehicle_type_display || review.vehicle.vehicle_type}</td>
                            </tr>
                            <tr>
                                <td><strong>载重:</strong></td>
                                <td>${review.vehicle.capacity} 吨</td>
                            </tr>
                            <tr>
                                <td><strong>尺寸:</strong></td>
                                <td>${review.vehicle.length || '无'}米 × ${review.vehicle.width || '无'}米 × ${review.vehicle.height || '无'}米</td>
                            </tr>
                            <tr>
                                <td><strong>行驶证号:</strong></td>
                                <td>${review.vehicle.vehicle_license || '无'}</td>
                            </tr>
                            <tr>
                                <td><strong>状态:</strong></td>
                                <td>${review.vehicle.status_display || review.vehicle.status}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-12">
                        <h6>车辆证件图片</h6>
                        <div class="image-gallery">
                            ${review.vehicle.vehicle_image ? `
                            <div>
                                <p>车辆照片</p>
                                <img src="${review.vehicle.vehicle_image}" alt="车辆照片" class="img-thumbnail" onclick="enlargeImage('${review.vehicle.vehicle_image}')">
                            </div>
                            ` : ''}
                            ${review.vehicle.vehicle_license_image ? `
                            <div>
                                <p>行驶证</p>
                                <img src="${review.vehicle.vehicle_license_image}" alt="行驶证" class="img-thumbnail" onclick="enlargeImage('${review.vehicle.vehicle_license_image}')">
                            </div>
                            ` : ''}
                        </div>
                    </div>
                    ` : ''}
                    <div class="col-12">
                        <h6>审核说明</h6>
                        <p>${review.reason || '无'}</p>
                    </div>
                </div>
            `;
            
            // 如果是待审核状态，添加操作按钮
            if (review.status === 'pending') {
                html += `
                    <div class="mt-4">
                        <button class="btn btn-success" onclick="showApproveModal(${review.id}, 'approved')">
                            通过
                        </button>
                        <button class="btn btn-danger" onclick="showApproveModal(${review.id}, 'rejected')">
                            拒绝
                        </button>
                    </div>
                `;
            }
            // 如果是已通过状态，添加打回按钮
            else if (review.status === 'approved') {
                html += `
                    <div class="mt-4">
                        <button class="btn btn-warning" onclick="showRejectModal(${review.id})">
                            打回审核
                        </button>
                    </div>
                `;
            }
            
            document.getElementById('reviewDetail').innerHTML = html;
        }
        
        // 显示审核操作模态框
        function showApproveModal(id, status) {
            document.getElementById('reviewId').value = id;
            document.getElementById('status').value = status;
            document.getElementById('reason').value = '';
            
            const modal = new bootstrap.Modal(document.getElementById('approveModal'));
            modal.show();
        }
        
        // 显示打回操作模态框
        function showRejectModal(id) {
            document.getElementById('reviewId').value = id;
            document.getElementById('status').value = 'rejected';
            document.getElementById('reason').value = '';
            
            const modal = new bootstrap.Modal(document.getElementById('approveModal'));
            modal.show();
        }
        
        // 提交审核结果
        function submitApprove(id) {
            const status = document.getElementById('status').value;
            const reason = document.getElementById('reason').value;
            
            fetch(`/api/admin/review/${id}/approve/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    status: status,
                    reason: reason
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('审核失败: ' + data.error);
                } else {
                    alert('审核已提交');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('approveModal'));
                    modal.hide();
                    // 重新加载详情
                    fetchReviewDetail(id);
                    // 更新统计信息
                    fetchStats();
                }
            })
            .catch(error => {
                console.error('审核失败:', error);
                alert('审核失败');
            });
        }
        
        // 工具函数：获取审核类型显示文本
        function getReviewTypeDisplay(type) {
            switch (type) {
                case 'user': return '用户资质审核';
                case 'vehicle': return '车辆资质审核';
                default: return type;
            }
        }
        
        // 工具函数：获取状态显示文本
        function getStatusDisplay(status) {
            switch (status) {
                case 'pending': return '待审核';
                case 'approved': return '已通过';
                case 'rejected': return '已拒绝';
                default: return status;
            }
        }
        
        // 工具函数：获取状态CSS类
        function getStatusClass(status) {
            switch (status) {
                case 'pending': return 'status-pending';
                case 'approved': return 'status-approved';
                case 'rejected': return 'status-rejected';
                default: return '';
            }
        }
        
        // 工具函数：格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }
        
        // 工具函数：获取Cookie
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        
        // 图片放大功能
        function enlargeImage(src) {
            document.getElementById('enlargedImage').src = src;
            const modal = new bootstrap.Modal(document.getElementById('imageModal'));
            modal.show();
        }
    </script>
</body>
</html>